import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import '../../core/config/app_config.dart';

class StorageService {
  static SharedPreferences? _prefs;

  static Future<void> init() async {
    _prefs = await SharedPreferences.getInstance();
  }

  // Token management
  Future<void> saveToken(String token) async {
    if (_prefs == null) {
      throw Exception('StorageService not initialized. Call StorageService.init() first.');
    }
    final success = await _prefs!.setString(AppConfig.keyToken, token);
    if (!success) {
      throw Exception('Failed to save token to SharedPreferences');
    }
  }

  Future<String?> getToken() async {
    if (_prefs == null) {
      return null;
    }
    return _prefs!.getString(AppConfig.keyToken);
  }

  Future<void> clearToken() async {
    await _prefs?.remove(AppConfig.keyToken);
  }

  // User ID management
  Future<void> saveUserId(int userId) async {
    await _prefs?.setInt(AppConfig.keyUserId, userId);
  }

  Future<int?> getUserId() async {
    return _prefs?.getInt(AppConfig.keyUserId);
  }

  Future<void> clearUserId() async {
    await _prefs?.remove(AppConfig.keyUserId);
  }

  // User info management
  Future<void> saveUserInfo(String userInfoJson) async {
    await _prefs?.setString(AppConfig.keyUserInfo, userInfoJson);
  }

  Future<String?> getUserInfo() async {
    return _prefs?.getString(AppConfig.keyUserInfo);
  }

  Future<void> clearUserInfo() async {
    await _prefs?.remove(AppConfig.keyUserInfo);
  }

  // Subscription ID management (for WebSocket)
  Future<void> saveSubscriptionId(String subscriptionId) async {
    await _prefs?.setString(AppConfig.keySubscriptionId, subscriptionId);
  }

  Future<String?> getSubscriptionId() async {
    return _prefs?.getString(AppConfig.keySubscriptionId);
  }

  Future<void> clearSubscriptionId() async {
    await _prefs?.remove(AppConfig.keySubscriptionId);
  }

  // Message storage management
  /// 获取消息存储键名（基于用户openId）
  Future<String> getMessagesStorageKey(String? userId) async {
    if (userId == null || userId.isEmpty) {
      throw Exception('无法获取用户ID，请先登录');
    }
    return 'chat_messages_$userId';
  }

  /// 保存消息列表到本地存储
  Future<void> saveMessages(String userId, List<Map<String, dynamic>> messages) async {
    if (_prefs == null) {
      throw Exception('StorageService not initialized. Call StorageService.init() first.');
    }
    final storageKey = await getMessagesStorageKey(userId);
    final messagesJson = jsonEncode(messages);
    await _prefs!.setString(storageKey, messagesJson);
  }

  /// 从本地存储加载消息列表
  Future<List<Map<String, dynamic>>> loadMessages(String userId) async {
    if (_prefs == null) {
      return [];
    }
    final storageKey = await getMessagesStorageKey(userId);
    final messagesJson = _prefs!.getString(storageKey);
    if (messagesJson == null || messagesJson.isEmpty) {
      return [];
    }
    try {
      final messages = jsonDecode(messagesJson) as List;
      return messages.cast<Map<String, dynamic>>();
    } catch (e) {
      return [];
    }
  }

  /// 清空指定用户的消息缓存
  Future<void> clearMessages(String userId) async {
    if (_prefs == null) {
      return;
    }
    final storageKey = await getMessagesStorageKey(userId);
    await _prefs!.remove(storageKey);
  }

  // Clear all data
  Future<void> clearAll() async {
    await clearToken();
    await clearUserId();
    await clearUserInfo();
    await clearSubscriptionId();
  }
}

